package com.nuanshui.heatedloan.middleware.rabbitmq.listener;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.rabbitmq.client.Channel;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.enums.RabbitMessageType;

/**
 * 普通消息处理类（以及弃用不建议再使用）
 * @param 
 * @author guohao
 * @date 2017年2月10日 上午10:49:28
 * @since $
 */
@Component
@Deprecated
public class RabbitmqCommonMessageListener {

	private static final  List<String> notOwner = Lists.newArrayList();
	
	@Autowired
	private RabbitAdmin rabbitAdmin;
	private Logger logger = LoggerFactory.getLogger(RabbitmqCommonMessageListener.class);
	//@RabbitListener(queues={"common_message_queue"})
	public void onCommonMessage(Message message, Channel channel) throws Exception {
		
		
		MessageProperties messageProperties =  message.getMessageProperties();
		//获取routeKey
		String routeKey = messageProperties.getReceivedRoutingKey();
		if(notOwner.contains(routeKey)) {//不支持
			String string = new String(message.getBody());
			logger.info(routeKey+  "不存在了"+"  "+string);
			//channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
			return;
		}
		if(routeKey.startsWith(RabbitMessageType.COMMON.getCode())) {
			String queue = routeKey.substring(RabbitMessageType.COMMON.getCode().length());
			try {
				RabbitmqMessageHandler messageHandler = SpringContextUtil.getBean(queue);
				if(messageHandler!=null) {
					messageHandler.onMessage(message, channel);
				}else {
					notOwner.add(routeKey);
					logger.info(routeKey+  "不支持");
					channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
				}
			} catch (Exception e) {
				e.printStackTrace();
			   channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
			}
			
		}		
	}
}
